package com.ldk.framework.service.impl;

import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.SystemUtil;

import org.apache.commons.collections.map.HashedMap;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.framework.entity.PlatformFundFlowRecord;
import com.ldk.framework.entity.RechargeRecord;
import com.ldk.framework.entity.TicketLevel;
import com.ldk.framework.entity.TicketRelate;
import com.ldk.framework.enums.FlowInOut;
import com.ldk.framework.enums.FlowPurpose;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.RechargeFrom;
import com.ldk.framework.enums.RechargeType;
import com.ldk.framework.service.IPlatformFundFlowRecordService;
import com.ldk.framework.service.IPlatformUserService;
import com.ldk.framework.service.IRechargeRecordService;
import com.ldk.framework.service.ITicketLevelService;
import com.ldk.framework.service.ITicketRelateService;
import com.ldk.framework.service.ITicketUserService;
import com.ldk.framework.dao.ITicketUserDAO;
import com.ldk.framework.entity.TicketUser;

import java.util.List;
import java.util.Map;

/**
 * TicketUserService接口实现类
 *
 * @author mqy
 */
@Service
public class TicketUserService extends BaseService<TicketUser> implements ITicketUserService {

    @Autowired
    private ITicketUserDAO ticketUserDAO;

    @Autowired
    private ITicketRelateService ticketRelateService;
    @Autowired
    private ITicketLevelService ticketLevelService;
    @Autowired
    protected IPlatformFundFlowRecordService platformFundFlowRecordService;
    @Autowired
    protected IRechargeRecordService rechargeRecordService;

    @Override
    protected IBaseDAO<TicketUser> getBaseDao() {
        return this.ticketUserDAO;
    }

    @Override
    public TicketUser getTicketInfoByPhoneNo(String dbKey, String phoneNo) {
        try {
            TicketUser query = new TicketUser();
            query.setPhoneNo(phoneNo);
            return selectOne(dbKey, query);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }


    @Override
    public TicketUser getTicketInfoBySaleNo(String dbKey, String saleNo) {
        try {
            TicketUser query = new TicketUser();
            query.setSaleNo(saleNo);
            return selectOne(dbKey, query);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    @Override
    public String generateSaleNo(String dbKey) {
        String saleNo = String.format("%06d", SystemUtil.generateRandom(999999));
        TicketUser ticketUser = getTicketInfoBySaleNo(dbKey, saleNo);
        if (ticketUser != null) {
            generateSaleNo("");
        } else {
            return saleNo;
        }
        return null;
    }

    @Override
    public Boolean saveTicketBySaleNo(String dbKey, String phoneNo, TicketUser ticketUser) {
        if (ticketUser == null) {
            return false;
        }
        //保存我的上级用户
        TicketRelate relate = new TicketRelate();
        relate.setPhoneNo(phoneNo);
        relate.setLevelPhone(ticketUser.getPhoneNo());
        relate.setLevelName(ticketUser.getUserName());
        relate.setLevelType(1);
        relate.setEnabled(true);
        relate.setCreateTime(SystemUtil.getAllSeconds());
        int row = ticketRelateService.insert(dbKey, relate);
        if (row > 0) {
            //新增我的上级的下线数量
            TicketUser user1 = new TicketUser();
            user1.setId(ticketUser.getId());
            user1.setRecNum(ticketUser.getRecNum() + 1);
            updateByKey(dbKey, user1);
        }
        //保存我的上上级
        if (row > 0 && !TextUtils.isEmpty(ticketUser.getLevel1Phone())) {
            TicketUser ticketUser1 = getTicketInfoByPhoneNo(dbKey, ticketUser.getLevel1Phone());
            if (ticketUser1 != null) {
                TicketRelate relate1 = new TicketRelate();
                relate1.setPhoneNo(phoneNo);
                relate1.setLevelPhone(ticketUser1.getPhoneNo());
                relate1.setLevelName(ticketUser1.getUserName());
                relate1.setLevelType(2);
                relate1.setEnabled(true);
                relate1.setCreateTime(SystemUtil.getAllSeconds());
                int row1 = ticketRelateService.insert(dbKey, relate1);
                if (row1 > 0) {
                    //新增我的上上级的下线数量
                    TicketUser user2 = new TicketUser();
                    user2.setId(ticketUser1.getId());
                    user2.setRecNum(ticketUser1.getRecNum() + 1);
                    updateByKey(dbKey, user2);
                }
            }
        }
        return row > 0;
    }

    @Override
    public Map<String, Double> calcatePrice(String dbKey, String phoneNo, String tripNo, double totalPrice) {
        if (phoneNo == null) {
            return null;
        }
        double price1 = 0.0;
        double price2 = 0.0;

        double rate1 = 0.0;
        double rate2 = 0.0;
        TicketRelate query = new TicketRelate();
        query.setPhoneNo(phoneNo);
        List<TicketRelate> result = ticketRelateService.selectList(dbKey, query);
        if (result != null && result.size() > 0) {
            for (TicketRelate rel : result) {
                TicketUser ticketUser = getTicketInfoByPhoneNo(dbKey, rel.getLevelPhone());
                if (ticketUser != null) {
                    TicketLevel querylevel = new TicketLevel();
                    querylevel.setLevel(ticketUser.getLevel());
                    TicketLevel ticketLevel = ticketLevelService.selectOne(dbKey, querylevel);
                    double rate = 0.0;
                    if (ticketLevel != null) {
                        if (rel.getLevelType() == 1) {
                            rate1 = ticketLevel.getRate1();
                            rate = ticketLevel.getRate1();
                        }
                        if (rel.getLevelType() == 2) {
                            rate2 = ticketLevel.getRate2();
                            rate = ticketLevel.getRate2();
                        }
                    }
                    //计算推荐人金额
                    if (rate > 0.0) {
                        double price = ConvertUtil.toFiexd(totalPrice * rate);
                        if (price < 0)
                            price = 0;
                        if (rel.getLevelType() == 1) {
                            price1=price;
                        }
                        if (rel.getLevelType() == 2) {
                            price2=price;
                        }
                        double beforeBalance = ticketUser.getBalance() == null ? 0 : ticketUser.getBalance();
                        double afterBalance = beforeBalance + price;
                        //司机总收入
                        double income = ticketUser.getIncome() == null ? 0 : ticketUser.getIncome();
                        income += price;

                        //更新票务经理余额
                        TicketUser driverEntity = new TicketUser();
                        driverEntity.setId(ticketUser.getId());
                        driverEntity.setBalance(afterBalance);
                        driverEntity.setIncome(income);
                        updateByKey(dbKey, driverEntity);
                        //插入充值记录
                        RechargeRecord record = new RechargeRecord();
                        record.setRecordNo(SystemUtil.generateRandomNo(""));
                        record.setPhoneNo(ticketUser.getPhoneNo());
                        record.setUserType(PlatformUserType.TICKET_USER.getValue());
                        record.setRechargeMoney(price);
                        record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                        record.setBeforeBalance(beforeBalance);
                        record.setAfterBalance(afterBalance);
                        record.setRechargeTime(SystemUtil.getAllSeconds());
                        record.setRechargeType(RechargeType.TICKET.getValue());
                        record.setOperator("system");
                        record.setRemark("票务经理推销用户完成城际通订单提成");
                        record.setLinkTaskNo(tripNo);
                        rechargeRecordService.insert(dbKey, record);

                        //添加平台流水出账记录
                        PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
                        flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                        flowRecord.setUserUniqueId(ticketUser.getPhoneNo());
                        flowRecord.setUserType(PlatformUserType.TICKET_USER.getValue());
                        flowRecord.setFlowAmount(price);
                        flowRecord.setInOut(FlowInOut.OUT.getValue());
                        flowRecord.setFlowFrom("平台");
                        flowRecord.setFlowTo("票务经理余额");
                        flowRecord.setFlowMode(0);
                        flowRecord.setLinkNo(tripNo);
                        flowRecord.setPurpose(FlowPurpose.TICKET_RECHARGE.getName());
                        platformFundFlowRecordService.insert(dbKey, flowRecord);
                    }
                }
            }
        }
        //

        Map<String, Double> maps = new HashedMap();
        maps.put("price1", price1);
        maps.put("price2", price2);
        return maps;
    }


}
